package cn.huiyunche.base.service.framework.security;

import cn.huiyunche.base.service.framework.utils.AppUtils;
import cn.huiyunche.base.service.vo.UserVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证成功需要向前台返回jwt.
 *
 * @author zhaoshb
 * @since 0.0.1
 */
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private String secureKey = null;

    public JwtAuthenticationSuccessHandler(String secureKey) {
        this.secureKey = secureKey;
    }

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserVo user = (UserVo) authentication.getPrincipal();
        String captcha = request.getParameter("captcha");
        String token = JwtUtils.generateToken(user, this.getSecureKey());

        JSONObject jsonObject = AppUtils.generateSuccessJson();
        jsonObject.put(JwtAuthenicationFilter.HEADER_AUTHORIZATION, JwtAuthenicationFilter.PREFIX_AUTHORIZATION + token);

        AppUtils.responseJson(response, jsonObject);
    }

    public void setSecureKey(String secureKey) {
        this.secureKey = secureKey;
    }

    private String getSecureKey() {
        return this.secureKey;
    }
}
